package com.gitee.dolt.boot.controller;

import cn.hutool.core.util.ReflectUtil;
import com.gitee.dolt.annotation.security.PreAuth;
import com.gitee.dolt.annotation.log.SysLog;
import com.gitee.dolt.core.base.Result;
import com.gitee.dolt.core.base.entity.SuperEntity;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.lang.reflect.Field;


/**
 * 新增
 *
 * @author LYH
 */
public interface SaveController<Entity, SaveDTO> extends BaseController<Entity> {

    /**
     * 新增
     *
     * @param dto 新增参数
     * @return
     */
    @ApiOperation(value = "新增")
    @PostMapping
    @SysLog(value = "新增")
    @PreAuth("hasAnyPermission('{}add')")
    default Result save(@RequestBody @Validated(SuperEntity.Save.class) SaveDTO dto) {
        Result result = handlerSave(dto);
        if (result.isExecDefault()) {
            Entity entity = toBean(dto);
            setNullValue(entity);
            if (entity instanceof SuperEntity) {
                ((SuperEntity) entity).setId(null);
            } else {
                Field field = ReflectUtil.getField(entity.getClass(), SuperEntity.FIELD_ID);
                if (field != null) {
                    ReflectUtil.setFieldValue(entity, field, null);
                }
            }
            getBaseService().save(entity);
            result.setData(entity);
        }
        return result;
    }

    /**
     * 自定义新增
     *
     * @param dto dto
     * @return 返回execDefault=true, 调用默认更新, 返回其他不调用默认更新
     */
    default Result handlerSave(SaveDTO dto) {
        return Result.execDefault(true);
    }


}
